import 'package:enterprise_v6_app/app/components/dialog/custom_responsible_person.dart';
import 'package:enterprise_v6_app/app/components/dialog/exit_tips.dart';
import 'package:enterprise_v6_app/app/components/special_operation/common_special_methods.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/special_job_code.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/page_base_drawer.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/ticket_plan_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/blind_plate_job_application/blind_plate_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/electricity_job_application/electricity_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/fire_job_application/fire_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/ground_job_application/ground_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/height_job_application/height_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/hoisting_job_application/hoisting_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/restricted_job_application/restricted_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/application/road_job_application/road_job_application_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_process/common_gas_analysis/common_gas_analysis_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_process/common_job_approval/common_job_approval_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_process/common_job_closed/common_job_closed_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_process/common_safety_disclosure/common_job_disclosure_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_process/common_security_measures/common_security_measures_view.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/special_list_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class CommonWorkAllController extends GetxController {
  ///小票id
  late String businessId;

  ///流程唯一编码
  late String processEncoding;

  ///小票作业状态 0：待开票 1：开票中 2：进行中 3：中断 4：已验收
  late int receiptType;

  ///1：动火作业 2：受限空间作业 3：盲板抽堵作业 4：高处作业 5：吊装作业 6：临时用电作业 7：动土作业 8：断路作业
  late String businessType;

  /// 小票实体类
  late TicketPlanReceiptLists ticketBean;

  ///外部列表controller
  final specialListController = Get.find<SpecialListController>();

  ///流程执行节点实体
  ExecuteEntity executeEntity = ExecuteEntity();

  /// scaffoldKey
  final scaffoldKey = GlobalKey<ScaffoldState>();

  ///左侧节点数据
  List<PageBaseEntity> titleList = [];

  ///审批节点编号
  int jobApprovalIndex = 0;

  ///审批节点是否已经执行
  bool approvalExecuted = false;

  /// 流程中正在执行的节点
  int processIndex = 0;

  ///节点信息
  List<ProcessNodesEntity> nodeList = [];

  /// 右侧页面选择菜单
  List<String> rightMenuList = [];

  /// 当前登录人是否为监护人
  bool isGuardian = false;

  /// 是否在交接班中 true:交接班中 false:正常状态
  bool isChange = false;

  @override
  void onInit() {
    super.onInit();
    final Map<String, dynamic> argumentsMap = Get.arguments as Map<String, dynamic>;
    ticketBean = argumentsMap['ticketBean'] as TicketPlanReceiptLists;
    businessId = ticketBean.id!;
    processEncoding = ticketBean.processEncoding!;
    receiptType = ticketBean.type!;
    businessType = argumentsMap['businessType'] as String;
    isChange = ticketBean.isChange == 1;
    setIsGuardian();
    getProcessNodes();
  }

  /// 判断当前登录人是否为监护人
  void setIsGuardian() {
    for (var item in ticketBean.guardianList) {
      if (item.operatorUserId == UserManager.getUserId()) {
        isGuardian = true;
        break;
      }
    }
  }

  ///判断右侧按钮显示
  void initRightMenu() {
    //开票中
    if (receiptType != 2 && !isChange) {
      rightMenuList = [
        '详情',
        '作业票',
      ];
    } else {
      rightMenuList = ['详情', '作业票', '管理'];
    }
  }

  ///  点击右侧菜单
  ///  [name] 名称
  void jumpToPage(String name) {
    switch (name) {
      case '详情':
        Get.toNamed(AppRoutes.workDetailAll, arguments: {
          'ticketReceiptId': executeEntity.ticketReceiptId,
          'processEncoding': processEncoding,
        });
        break;
      case '作业票':
        Get.toNamed(AppRoutes.jobTicket, arguments: {
          'id': ticketBean.ticketPlanId,
          'businessType': businessType,
        });
        break;
      case '管理':
        Get.back();
        Get.toNamed(AppRoutes.manageJobs, arguments: ticketBean);
        break;
    }
  }

  /// 判断当前节点按钮显示字段
  bool isNextStep() {
    // 选择的节点为执行节点
    if (executeEntity.selectIndex == processIndex) {
      return true;
    } else {
      return false;
    }
  }

  /// 判断是否显示撤销按钮
  bool isShowRevoke() {
    return receiptType == 1;
  }

  /// 判断是否显示下一步，修改按钮
  bool isShowNextButton() {
    return isEnabled(nodeList[executeEntity.selectIndex], executeEntity.selectIndex);
  }

  /// 判断当前节点是否可以编辑、提交
  /// [nodeEntity] 节点信息
  /// [index] 节点序号
  bool isEnabled(ProcessNodesEntity nodeEntity, int index) {
    // 登录人是否为节点执行人
    bool isExecutor = false;
    for (var item in nodeEntity.rtUserProcesses!) {
      if (item.userId == UserManager.getUserId()) {
        isExecutor = true;
      }
    }
    // 不为节点执行人且不为监护人
    if (!isExecutor && !isGuardian) {
      return false;
    }
    //当前执行节点
    if (nodeEntity.executableOrNot == 1) {
      return true;
    }
    // 选择节点大于执行节点
    if (index > processIndex) {
      return false;
    }
    // 如果是开票中和进行中的气体分析节点可以进行编辑
    if ((receiptType == 1 || receiptType == 2) && nodeEntity.appRoutingAddress == SpecialJobCode.gasAnalysis) {
      return true;
    }
    // return false;
    //判断是否已经审批,并且在审批节点之前
    if (approvalExecuted && index < jobApprovalIndex) {
      return false;
    }
    //审批节点之后
    if (index >= jobApprovalIndex) {
      return false;
    }
    return true;
  }

  /// 获取流程节点数据
  void getProcessNodes() async {
    //获取数据
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(Interface.getProcessNodesByBusinessId,
        queryParameters: {'processEncoding': processEncoding, 'businessId': businessId}).execute(isShowLoading: true);

    //查询到节点数据
    res.onSuccess((result) async {
      nodeList = result.data!;
      //剔除开始和结束节点
      nodeList = nodeList.where((element) => element.nodeType != 3 && element.nodeType != 4).toList();
      //先找到当前的执行节点
      for (int i = 0; i < nodeList.length; i++) {
        final ProcessNodesEntity item = nodeList[i];
        //当前执行节点
        if (item.executableOrNot == 1) {
          processIndex = i;
          executeEntity.selectIndex = i;
          executeEntity.nodeId = item.nodeId;
          executeEntity.processEncoding = item.processEncoding;
        }
        //作业审批节点信息
        if (item.appRoutingAddress == SpecialJobCode.jobApproval) {
          jobApprovalIndex = i;
          approvalExecuted = (item.executableOrNot == 3);
        }
      }
      //设置作业票id
      executeEntity.ticketReceiptId = businessId;
      //清空数据
      titleList.clear();
      //添加数据到页面
      for (int i = 0; i < nodeList.length; i++) {
        final ProcessNodesEntity item = nodeList[i];
        switch (nodeList[i].appRoutingAddress) {
          //作业申请
          case SpecialJobCode.jobApplication:
            //根据类型,添加节点页面
            addJobApplicationPageByType(item: item, isEnabled: isEnabled(nodeList[i], i));
            break;
          //气体分析
          case SpecialJobCode.gasAnalysis:
            //根据类型,添加节点页面
            // addGasAnalysisPageByType(item: item, isEnabled: isEnabled(nodeList[i], i));
            titleList.add(PageBaseEntity(
              title: item.nodeName ?? '',
              icon: AppImages.icon_safety_measures,
              expandTitle: item.nodeName ?? '',
              currentPageTitle: 0,
              pages: [
                CommonGasAnalysisPage(
                  isEnabled: isEnabled(nodeList[i], i),
                  isChange: isChange,
                  businessType: businessType,
                )
              ],
            ));
            break;
          //安全措施
          case SpecialJobCode.safetyMeasures:
            titleList.add(PageBaseEntity(
              title: item.nodeName ?? '',
              icon: AppImages.icon_safety_measures,
              expandTitle: item.nodeName ?? '',
              currentPageTitle: 0,
              pages: [
                CommonSecurityMeasuresPage(
                  isEnabled: isEnabled(nodeList[i], i),
                  isChange: isChange,
                )
              ],
            ));
            break;
          //安全交底
          case SpecialJobCode.safetyDisclosure:
            titleList.add(PageBaseEntity(
              title: item.nodeName ?? '',
              icon: AppImages.icon_safety_disclosure,
              expandTitle: item.nodeName ?? '',
              currentPageTitle: 0,
              pages: [
                CommonSafetyDisclosurePage(
                  isEnabled: isEnabled(nodeList[i], i),
                  isChange: isChange,
                )
              ],
            ));
            break;
          //作业审批
          case SpecialJobCode.jobApproval:
            titleList.add(PageBaseEntity(
              title: item.nodeName ?? '',
              icon: AppImages.icon_job_approval,
              expandTitle: item.nodeName ?? '',
              currentPageTitle: 0,
              pages: [
                CommonJobApprovalPage(
                  isEnabled: isEnabled(nodeList[i], i),
                  isChange: isChange,
                )
              ],
            ));
            break;
          //作业关闭
          case SpecialJobCode.jobClose:
            titleList.add(PageBaseEntity(
              title: item.nodeName ?? '',
              icon: AppImages.icon_job_close,
              expandTitle: item.nodeName ?? '',
              currentPageTitle: 0,
              pages: [
                CommonJobClosedPage(
                  isEnabled: isEnabled(nodeList[i], i),
                )
              ],
            ));
            break;
        }
      }
      update();
    });

    //失败
    res.onError((result) {
      AppToast.showWarning('请求失败');
    });
  }

  /// 根据不同类型,添加不同作业申请页面
  /// [item] 流程节点类
  void addJobApplicationPageByType({required ProcessNodesEntity item, required bool isEnabled}) {
    final PageBaseEntity bean = PageBaseEntity(
      title: item.nodeName ?? '',
      icon: AppImages.icon_job_application_blue,
      expandTitle: item.nodeName ?? '',
      currentPageTitle: 0,
      pages: [],
    );
    //判断作业类型
    switch (businessType) {
      // 动火作业
      case '1':
        bean.pages = [FireJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
      // 受限空间
      case '2':
        bean.pages = [RestrictedJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
        break;
      // 盲板抽堵
      case '3':
        bean.pages = [BlindPlateJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
        break;
      // 高处作业
      case '4':
        bean.pages = [HeightJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
        break;
      // 吊装作业
      case '5':
        bean.pages = [HoistingJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
        break;
      // 临时用电
      case '6':
        bean.pages = [ElectricityJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
        break;
      // 动土作业
      case '7':
        bean.pages = [GroundJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
        break;
      // 断路作业
      case '8':
        bean.pages = [RoadJobApplicationPage(isEnabled: isEnabled, isChange: isChange)];
        break;
      default:
        break;
    }
    // 如果不为空,则添加
    if (bean.pages.isNotEmpty) {
      titleList.add(bean);
    }
  }

  /// 点击左侧菜单
  /// [index] 索引
  void selectLeftMenu(int index) {
    if (executeEntity.selectIndex != index) {
      if (receiptType == 1 || receiptType == 2) {
        Get.dialog<bool>(ExitTips(
          content: '切换节点后,当前节点所填信息将不支持继续编辑，是否继续切换节点？',
          func: (v) {
            if (v) {
              executeEntity.selectIndex = index;
              update();
            }
          },
        ));
      } else {
        executeEntity.selectIndex = index;
        update();
      }
    }
  }

  /// title选择切换
  /// [titleIndex] 标题索引
  /// [index] 页面索引
  void selectTitle(int titleIndex, int index) {
    titleList[titleIndex].currentPageTitle = index;
    update();
  }

  /// 撤销作业票
  void revokeTicketReceipt() {
    Get.dialog<bool>(
      ExitTips(
        content: '是否确认撤销当前作业票？',
        func: (v) async {
          if (v) {
            //获取数据
            final res = await HttpUtil()
                .generateGetRequest(Interface.revokeTicketReceipt, queryParameters: {'ticketReceiptId': executeEntity.ticketReceiptId}).execute();
            res.onSuccess((result) {
              //外部列表controller
              final specialListController = Get.find<SpecialListController>();
              specialListController.refreshPage();
              //关闭当前页面
              Get.back();
              AppToast.showSuccess('撤销成功');
            });
          }
        },
      ),
    );
  }

  /// 点击展开菜单
  /// [index] 索引
  void selectExpandMenu(int index) {
    Get.back();
    update();
  }

  /// ****************************** 下一步 作业票流程执行统一处理 ******************************//
  void nextStep() {
    executeEntity.nodeId = nodeList[executeEntity.selectIndex].nodeId;
    executeEntity.processEncoding = processEncoding;
    executeEntity.rtemplateId = nodeList[executeEntity.selectIndex].rtemplateId;
    //判断当前执行的节点
    // if (processIndex != executeEntity.selectIndex) {
    //   AppToast.showWarning('当前选择节点不可执行!');
    //   return;
    // }
    if (!isEnabled(nodeList[executeEntity.selectIndex], executeEntity.selectIndex)) {
      AppToast.showWarning('当前选择节点不可执行!');
      return;
    }
    switch (nodeList[executeEntity.selectIndex].appRoutingAddress) {
      // 作业申请
      case SpecialJobCode.jobApplication:
        CommonSpecialMethods.executeJobApplication(
            businessType: businessType, ticketReceipt: executeEntity.ticketReceiptList!, onNext: nextStepResponsiblePersonDialog);
        // executeJobApplication();
        break;
      // 气体分析
      case SpecialJobCode.gasAnalysis:
        executeGasAnalysis();
        break;
      // 安全措施
      case SpecialJobCode.safetyMeasures:
        executeSafetyMeasures();
        break;
      // 安全交底
      case SpecialJobCode.safetyDisclosure:
        executeSafetyDisclosure();
        break;
      // 作业审批
      case SpecialJobCode.jobApproval:
        executeJobApproval();
        break;
      // 作业关闭
      case SpecialJobCode.jobClose:
        executeJobClose();
        break;
    }
    // if (selectIndex < titleList.length - 1) {
    //   selectIndex++;
    //   update();
    // }
  }

  /// ****************************** 执行气体分析节点 ******************************//

  void executeGasAnalysis() {
    //气体分析节点数据
    final List<ExecuteTicketGasList> ticketGasList = executeEntity.ticketGasList!;
    if (CommonSpecialMethods.gasAnalysisNotFilledIn(ticketGasList: ticketGasList, businessType: businessType)) {
      return;
    }
    // 设置为不可编辑数据
    for (var item in ticketGasList) {
      item.isNewData = false;
    }
    //判断是否还有下一节点,有就弹出下一节点负责人选择弹窗
    nextStepResponsiblePersonDialog();
  }

  /// ****************************** 执行安全措施节点 ******************************//
  void executeSafetyMeasures() {
    //安全措施节点数据
    final List<ExecuteWorkSafetyMeasuresList> safetyMeasuresList = executeEntity.workSafetyMeasuresList!;
    if (CommonSpecialMethods.safetyMeasuresNotFilledIn(safetyMeasuresList: safetyMeasuresList)) {
      return;
    }
    //判断是否还有下一节点,有就弹出下一节点负责人选择弹窗
    nextStepResponsiblePersonDialog();
  }

  /// ****************************** 执行安全交底节点 ******************************//
  void executeSafetyDisclosure() {
    //安全措施节点数据
    final List<ExecuteTicketDiscloseList> safetyDisclosureList = executeEntity.ticketDiscloseList!;
    if (CommonSpecialMethods.safetyDisclosureNotFilledIn(safetyDisclosureList: safetyDisclosureList)) {
      return;
    }
    //判断是否还有下一节点,有就弹出下一节点负责人选择弹窗
    nextStepResponsiblePersonDialog();
  }

  /// ****************************** 执行作业审批节点 ******************************//
  void executeJobApproval() {
    //作业审批节点数据
    if (executeEntity.startDate!.isEmpty) {
      AppToast.showWarning('请选择作业开始时间!');
      return;
    }
    final List<ExecuteWorkCheckList> workCheckList = executeEntity.workCheckLists!;
    if (CommonSpecialMethods.workCheckNotFilledIn(workCheckList: workCheckList)) {
      return;
    }
    //判断是否还有下一节点,有就弹出下一节点负责人选择弹窗
    nextStepResponsiblePersonDialog();
  }

  /// ****************************** 执行作业关闭节点 ******************************//
  void executeJobClose() {
    //作业审批节点数据
    if (executeEntity.endDate!.isEmpty) {
      AppToast.showWarning('请选择作业结束时间!');
      return;
    }
    final ExecuteWorkCheckList workCheck = executeEntity.workCheckList!;
    if (CommonSpecialMethods.workCheckNotFilledIn(workCheckList: [workCheck])) {
      return;
    }
    //判断是否还有下一节点,有就弹出下一节点负责人选择弹窗
    nextStepResponsiblePersonDialog();
  }

  ///是否还有下一节点
  bool isNextNode() {
    return executeEntity.selectIndex < nodeList.length - 1;
  }

  ///当前节点是否是修改节点
  bool isUpdate() {
    return executeEntity.selectIndex < processIndex;
  }

  ///下一节点负责人、或签名执行人选择弹窗
  void nextStepResponsiblePersonDialog() {
    if (!isNextNode() || isUpdate()) {
      // 没有下一节点,或为修改节点直接提交
      processExecute();
      return;
    }
    // 获取下一节点数据
    final ProcessNodesEntity nextNodeEntity = nodeList[executeEntity.selectIndex + 1];
    // 只有下一节点为安全交底和作业关闭时,才会进行人员选择,并且在为交接班时不进行选择
    if ((nextNodeEntity.appRoutingAddress == SpecialJobCode.safetyDisclosure || nextNodeEntity.appRoutingAddress == SpecialJobCode.jobClose) && !isChange) {
      final List<RolePersonnelEntity> rolePersonnelList = [];
      //判断下一节点是否有执行人
      if (nextNodeEntity.rtUserProcesses!.isNotEmpty) {
        rolePersonnelList.addAll(nextNodeEntity.rtUserProcesses!);
      }
      //弹出选择负责人弹窗
      Get.dialog<bool>(
        CustomResponsiblePerson(
          callback: (List<RolePersonnelEntity> entity) {
            if (entity.isNotEmpty) {
              // 设置下一个节点执行人
              executeEntity.nextNodeExecutor!.clear();
              executeEntity.nextNodeExecutor!.addAll(entity);
            }
            //提交数据,执行流程
            processExecute();
          },
          rolePersonnelList: rolePersonnelList,
          nodeType: nextNodeEntity.appRoutingAddress!,
          ticketReceiptId: businessId,
        ),
      );
    } else {
      // 其他节点直接提交
      processExecute();
    }
  }

  ///流程节点执行
  Future<void> processExecute() async {
    //获取数据
    final res = await HttpUtil().generatePostRequest(Interface.postProcessExecute, data: executeEntity.toJson()).execute(isShowLoading: true);
    res.onSuccess((result) {
      //如果还有下一个节点则获取新节点数据
      if (isNextNode()) {
        getProcessNodes();
      } else {
        //没有下一个节点,直接返回,并刷新列表
        Get.back(result: true);
      }
      specialListController.refreshPage();
      AppToast.showSuccess('提交成功');
    });
    res.onError((result) {
      AppToast.showError('提交失败');
    });
  }
}
